package com.example.huadu_server.admin.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.example.huadu_server.admin.dto.*;
import com.example.huadu_server.admin.dto.*;
import com.example.huadu_server.admin.dto.*;
import com.example.huadu_server.admin.entity.Admin;
import com.example.huadu_server.admin.service.AdminService;
import com.example.huadu_server.config.Response;
import com.example.huadu_server.house.service.HouseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;
    @Autowired
    private HouseService houseService;

    /**
     * 修改密码
     */
    @PostMapping("/modifyPass")
    public Response<String> modifyPassword(@RequestBody @Valid ModifyPasswordDTO modifyPasswordDTO) {
        int userId = StpUtil.getLoginIdAsInt();
        return adminService.modifyPassword(
                userId,
                modifyPasswordDTO.getOldPassword(),
                modifyPasswordDTO.getNewPassword(),
                modifyPasswordDTO.getConfirmPassword()
        );
    }

    /**
     * 获取验证码 (GET)
     */
    @GetMapping("/forgetPassCode")
    public Response<String> sendForgetPasswordCode(@RequestParam String email) {
        return adminService.sendForgetPasswordCode(email);
    }

    /**
     * 重置密码 (POST)
     */
    @PostMapping("/forgetPass")
    public Response<String> resetPassword(@RequestBody @Valid ForgetPasswordDTO forgetPasswordDTO) {
        return adminService.resetPassword(
                forgetPasswordDTO.getEmail(),
                forgetPasswordDTO.getCode(),
                forgetPasswordDTO.getNewPassword(),
                forgetPasswordDTO.getConfirmPassword()
        );
    }

    /**
     * 获取用户个人信息
     *
     * @return ResponseEntity<Response < User>>
     */
    @GetMapping("/userInfo")
    public ResponseEntity<Response<Admin>> getUserInfo() {
        // 获取当前登录用户的 ID
        int userId = StpUtil.getLoginIdAsInt();

        // 调用 Service 层获取用户信息
        Response<Admin> response = adminService.getUserInfoById(userId);

        return ResponseEntity.status(response.getCode()).body(response);
    }


    /**
     * 修改用户个人信息
     */
    @PostMapping("/updateInfo")
    public Response<String> updateUserInfo(@RequestBody @Valid UpdateInfoDTO updateInfoDTO) {
        int userId = StpUtil.getLoginIdAsInt(); // 获取当前登录用户的 ID
        return adminService.updateUserInfo(userId, updateInfoDTO);
    }

    /**
     * 获取修改邮箱验证码
     */
    @GetMapping("/getUpdateEmailCode")
    public Response<String> sendUpdateEmailCode(@RequestParam String email) {
        return adminService.sendUpdateEmailCode(email);
    }

    /**
     * 修改用户邮箱
     */
    @PostMapping("/updateEmail")
    public Response<String> updateUserEmail(@RequestBody @Valid UserInfoDTO userInfoDTO) {
        int userId = StpUtil.getLoginIdAsInt(); // 获取当前登录用户的 ID
        return adminService.updateUserEmail(userId, userInfoDTO);
    }

    /**
     * 上传用户头像
     */
    @PostMapping("/uploadLogo")
    public Response<String> uploadUserLogo(@RequestParam("file") MultipartFile file) {
        int userId = StpUtil.getLoginIdAsInt(); // 获取当前登录用户 ID

        // 检查是否上传文件---哪怕没有上传图片也会有默认值，所以先排除掉默认值再进行判断是否上传文件
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || originalFilename.isEmpty() ||
                originalFilename.startsWith("1735872250277_")) {
            return new Response<>(400, "请上传图片", null);
        }
        return adminService.uploadUserLogo(file, userId);
    }

    /**
     * 审核房屋
     * @param auditHouseDTO
     * @return
     */
    @PostMapping("/auditHouse")
    public ResponseEntity<Response<String>> auditHouse(@RequestBody AuditHouseDTO auditHouseDTO) {
        // 校验登录状态
        StpUtil.checkLogin();
        Response<String> response = houseService.auditHouse(
                auditHouseDTO.getHouseId(),
                auditHouseDTO.getNewStatus(),
                auditHouseDTO.getRemarks()
        );
        return ResponseEntity.status(response.getCode()).body(response);
    }

    /**
     * 获取待审核房屋列表
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("/getPendingHouses/{pageNo}/{pageSize}")
    public ResponseEntity<Response<Map<String, Object>>> getPendingHouses(
            @PathVariable int pageNo,
            @PathVariable int pageSize) {
        // 校验登录状态
        StpUtil.checkLogin();
        // 这里可以增加管理员角色校验逻辑，如有需要
        Response<Map<String, Object>> response = houseService.getPendingHouses(pageNo, pageSize);
        return ResponseEntity.status(response.getCode()).body(response);
    }

    /**
     * 管理员审核房源时尝试锁定房屋---避免多个管理员审核同一房源
     * @param houseId
     * @return
     */
    @PostMapping("/tryLockHouse/{houseId}")
    public ResponseEntity<Response<Boolean>> tryLockHouse(@PathVariable int houseId) {
        StpUtil.checkLogin();
        Response<Boolean> response = houseService.tryLockHouse(houseId);
        return ResponseEntity.status(response.getCode()).body(response);
    }

    /**
     * 获取已审核房屋列表
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("/getMyAuditHouses/{pageNo}/{pageSize}")
    public ResponseEntity<Response<Map<String, Object>>> getAuditedHouses(
            @PathVariable int pageNo,
            @PathVariable int pageSize) {
        // 校验登录状态
        StpUtil.checkLogin();
        // 从 Sa-Token 获取当前管理员的 ID
        int adminId = StpUtil.getLoginIdAsInt();
        Response<Map<String, Object>> response = houseService.getAuditedHousesByAdmin(adminId, pageNo, pageSize);
        return ResponseEntity.status(response.getCode()).body(response);
    }

    /**
     * 管理员下架房源
     * @param param
     * @return
     */
    @PostMapping("/removeHouse")
    public ResponseEntity<Response<String>> removeHouse(@RequestBody Map<String, Object> param) {
        StpUtil.checkLogin();
        int houseId = (Integer) param.get("houseId");
        String remarks = (String) param.get("remarks");
        Response<String> response = houseService.removeHouse(houseId, remarks);
        return ResponseEntity.status(response.getCode()).body(response);
    }

    /**
     * 获取所有用户列表
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("/getAllUsers/{pageNo}/{pageSize}")
    public ResponseEntity<Response<Map<String, Object>>> getAllUsers(
            @PathVariable int pageNo,
            @PathVariable int pageSize) {
        Response<Map<String, Object>> response = adminService.getAllUsers(pageNo, pageSize);
        return ResponseEntity.status(response.getCode()).body(response);
    }

    /**
     * 获取所有房东列表
     * @param pageNo 当前页码
     * @param pageSize 每页大小
     * @return 房东列表
     */
    @GetMapping("/getAllLandlords/{pageNo}/{pageSize}")
    public ResponseEntity<Response<Map<String, Object>>> getAllLandlords(
            @PathVariable int pageNo,
            @PathVariable int pageSize) {
        Response<Map<String, Object>> response = adminService.getAllLandlords(pageNo, pageSize);
        return ResponseEntity.status(response.getCode()).body(response);
    }

    /**
     * 禁用用户接口
     * @param param 包含用户ID、管理员密码、禁用理由
     * @return 操作结果
     */
    @PostMapping("/disableUser")
    public ResponseEntity<Response<String>> disableUser(@RequestBody Map<String, Object> param) {
        int userId = (Integer) param.get("id");
        String password = (String) param.get("password");
        String remarks = (String) param.get("remarks");

        Response<String> response = adminService.disableUser(userId, password, remarks);
        return ResponseEntity.status(response.getCode()).body(response);
    }

    /**
     * 恢复用户接口
     * @param param 包含用户ID、管理员密码
     * @return 操作结果
     */
    @PostMapping("/enableUser")
    public ResponseEntity<Response<String>> enableUser(@RequestBody Map<String, Object> param) {
        int userId = (Integer) param.get("id");
        String password = (String) param.get("password");

        // 恢复用户时，不需要remarks，默认邮件内容
        Response<String> response = adminService.enableUser(userId, password);
        return ResponseEntity.status(response.getCode()).body(response);
    }

    /**
     * 禁用房东接口
     * @param param 包含房东ID、管理员密码、禁用理由
     * @return 操作结果
     */
    @PostMapping("/disableLandlord")
    public ResponseEntity<Response<String>> disableLandlord(@RequestBody Map<String, Object> param) {
        int landlordId = (Integer) param.get("id");
        String password = (String) param.get("password");
        String remarks = (String) param.get("remarks");

        Response<String> response = adminService.disableLandlord(landlordId, password, remarks);
        return ResponseEntity.status(response.getCode()).body(response);
    }

    /**
     * 恢复房东接口
     * @param param 包含房东ID、管理员密码
     * @return 操作结果
     */
    @PostMapping("/enableLandlord")
    public ResponseEntity<Response<String>> enableLandlord(@RequestBody Map<String, Object> param) {
        int landlordId = (Integer) param.get("id");
        String password = (String) param.get("password");

        // 恢复房东时，不需要remarks，默认邮件内容
        Response<String> response = adminService.enableLandlord(landlordId, password);
        return ResponseEntity.status(response.getCode()).body(response);
    }

    /**
     * 获取总览统计数据
     * 返回数据包括：
     *  - 总租客数（用户表记录数）
     *  - 总房东数（房东表记录数）
     *  - 房源总量（房源表记录数）
     *  - 预约记录数量（预约表记录数）
     *  - 在线聊天记录数量（消息表记录数）
     *
     * @return ResponseEntity 包含统计数据的响应对象
     */
    @GetMapping("/getOverview")
    public ResponseEntity<Response<Map<String, Object>>> getOverviewStats() {
        // 校验登录状态
        StpUtil.checkLogin();
        Response<Map<String, Object>> response = adminService.getOverviewStats();
        return ResponseEntity.status(response.getCode()).body(response);
    }

    /**
     * 获取趋势统计数据
     * 接口支持根据 type（house、appointment、message）、startDate、endDate 以及 granularity（day、month、year）进行数据分组统计
     *
     * @param type        统计数据类型，如 "house"（房源）、"appointment"（预约）、"message"（聊天记录）
     * @param startDate   开始时间，格式如 "2025-01-01"
     * @param endDate     结束时间，格式如 "2025-01-31"
     * @param granularity 统计粒度：day、month 或 year
     * @return ResponseEntity 包含趋势统计数据的响应对象
     */
    @GetMapping("/getTrend")
    public ResponseEntity<Response<Map<String, Object>>> getTrendStats(
            @RequestParam String type,
            @RequestParam String startDate,
            @RequestParam String endDate,
            @RequestParam String granularity) {
        // 校验登录状态
        StpUtil.checkLogin();
        Response<Map<String, Object>> response = adminService.getTrendStats(type, startDate, endDate, granularity);
        return ResponseEntity.status(response.getCode()).body(response);
    }

    /**
     * 获取用户行为统计数据
     * 接口支持根据 metric（"browse"、"favorite"、"appointment"、"conversion"）、startDate、endDate 以及 granularity（day、month、year）进行分组统计
     *
     * @param metric      统计指标，如 "browse" 表示浏览，"favorite" 表示收藏，"appointment" 表示预约，"conversion" 表示预约转化率
     * @param startDate   开始日期，格式如 "2025-01-01"
     * @param endDate     结束日期，格式如 "2025-01-31"
     * @param granularity 统计粒度：day、month 或 year
     * @return ResponseEntity 包含统计数据的响应对象
     */
    @GetMapping("/getUserBehavior")
    public ResponseEntity<Response<Map<String, Object>>> getUserBehaviorStats(
            @RequestParam String metric,
            @RequestParam String startDate,
            @RequestParam String endDate,
            @RequestParam String granularity) {
        // 校验登录状态
        StpUtil.checkLogin();
        Response<Map<String, Object>> response = adminService.getUserBehaviorStats(metric, startDate, endDate, granularity);
        return ResponseEntity.status(response.getCode()).body(response);
    }


    /**
     * 获取房东运营情况统计数据：统计每个房东的房源发布数量及预约记录数量，帮助评估房东运营情况
     */
    @GetMapping("/getLandlordPerformance")
    public ResponseEntity<Response<List<Map<String, Object>>>> getLandlordPerformanceStats() {
        StpUtil.checkLogin();
        Response<List<Map<String, Object>>> response = adminService.getLandlordPerformanceStats();
        return ResponseEntity.status(response.getCode()).body(response);
    }

    /**
     * 获取房源在不同地理区域的分布统计数据
     * 传入参数 type 为 "business" 或 "subway"
     */
    @GetMapping("/getHouseByLocation")
    public ResponseEntity<Response<List<Map<String, Object>>>> getGeoDistribution(@RequestParam String type) {
        // 校验登录状态
        StpUtil.checkLogin();
        Response<List<Map<String, Object>>> response = adminService.getGeoDistribution(type);
        return ResponseEntity.status(response.getCode()).body(response);
    }
}
